package org.mx.spring.password;

import org.mx.utils.DigestUtils;
import org.mx.utils.SecretUtils;
import org.mx.utils.StringUtils;

/**
 * 密码读写器集合
 * 
 * @author john.peng
 *
 */
public class PasswordIOs {
	/**
	 * 创建一个Base64的密码读写器
	 * 
	 * @return PasswordIO
	 */
	public static PasswordIO Base64IO() {
		return new PasswordIO("base64") {
			@Override
			public String read(String encrypt) {
				if (StringUtils.isBlank(encrypt)) {
					return "";
				}
				return new String(DigestUtils.fromBase64(encrypt));
			}

			@Override
			public String write(String decrypt) {
				if (StringUtils.isBlank(decrypt)) {
					return "";
				}
				return DigestUtils.toBase64(decrypt.getBytes());
			}
		};
	}

	/**
	 * 创建一个基于SM4-Base64算法的密码读写器
	 * 
	 * @param secretKey 安全密钥
	 * @return PasswordIO
	 */
	public static PasswordIO Sm4Base64IO(String secretKey) {
		return new PasswordIO("sm4-base64") {
			@Override
			public String read(String encrypt) {
				if (StringUtils.isBlank(encrypt)) {
					return "";
				}
				return DigestUtils.toBase64(SecretUtils.encrypt_sm4_ecb(secretKey, encrypt.getBytes()));
			}

			@Override
			public String write(String decrypt) {
				if (StringUtils.isBlank(decrypt)) {
					return "";
				}
				return new String(SecretUtils.decrypt_sm4_ecb(secretKey, DigestUtils.fromBase64(decrypt)));
			}
		};
	};

	/**
	 * 创建一个基于3DES-Base64算法的密码读写器
	 * 
	 * @param secretKey 安全密钥
	 * @return PasswordIO
	 */
	public static PasswordIO Des3Base64IO(String secretKey) {
		return new PasswordIO("3des-base64") {
			@Override
			public String read(String encrypt) {
				if (StringUtils.isBlank(encrypt)) {
					return "";
				}
				return DigestUtils.toBase64(SecretUtils.encrypt_3des_168(secretKey, encrypt.getBytes()));
			}

			@Override
			public String write(String decrypt) {
				if (StringUtils.isBlank(decrypt)) {
					return "";
				}
				return new String(SecretUtils.decrypt_3des_168(secretKey, DigestUtils.fromBase64(decrypt)));
			}
		};
	}

	/**
	 * 创建一个基于AES-Base64算法的密码读写器
	 * 
	 * @param secretKey 安全密钥
	 * @return PasswordIO
	 */
	public static PasswordIO AesBase64IO(String secretKey) {
		return new PasswordIO("3des-base64") {
			@Override
			public String read(String encrypt) {
				if (StringUtils.isBlank(encrypt)) {
					return "";
				}
				return DigestUtils.toBase64(SecretUtils.encrypt_aes_256(secretKey, encrypt.getBytes()));
			}

			@Override
			public String write(String decrypt) {
				if (StringUtils.isBlank(decrypt)) {
					return "";
				}
				return new String(SecretUtils.decrypt_aes_256(secretKey, DigestUtils.fromBase64(decrypt)));
			}
		};
	}
}
